package Services

import(
	"github.com/gin-gonic/gin"
	"fmt"
	"net/http"
	"gin/Databases"
	"gin/Middlewares"
	"strconv"
)


func confirmMarketData(id int) bool {
	tx, err1 := Databases.Db.Begin()
	if err1 != nil {
		if tx != nil {
			_ = tx.Rollback()
		}
		fmt.Printf("begin trans action failed, err:%v\n", err1)
		return false
	}

	sql_insert := "insert into market_data (Fdate, Ftype, Ftitle, Furl, Fsite) select Fdate, Ftype, Ftitle, Furl, Fsite from market_data_temp where Fid = ?;"
	_,err2 := Databases.Db.Exec(sql_insert, id)
	if err2 != nil {
		_ = tx.Rollback()
		fmt.Println("delete failed, ", err2)
		return false
	}

	update_sql := "update market_data_temp set Fid=Fid + 20000000,Fstatus=1,Fmodify_time=now() where Fid=?;"
	_,err3 := Databases.Db.Exec(update_sql, id)
	if err3 != nil {
		_ = tx.Rollback()
		fmt.Println("delete failed, ", err3)
		return false
	}
	tx.Commit()
	return true
}


// 宏观数据
func MarketDataConfirm(c *gin.Context) {
	if (!Middlewares.CheckLogin(c)) {
		c.JSON(http.StatusOK, gin.H{
	        "result": -1,
	        "msg":    "login fail",
	        "data": "{}",
	    })
	    return
	}

	id, _ := strconv.Atoi(c.Query("id"))

	if (!confirmMarketData(id)) {
		c.JSON(http.StatusOK, gin.H{
	        "result": -2,
	        "msg":    "confirm fail",
	        "data": "{}",
	    })
	    return
	}

    c.JSON(http.StatusOK, gin.H{
        "result": 0,
        "msg":    "success",
        "data": "",
    })
}

